package com.googlecode.bizyap.core;

import java.io.InputStream;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

import com.googlecode.bizyap.core.logging.Logger;
import com.googlecode.bizyap.core.logging.LoggerFactory;


public class Authenticator {

	private static final Logger log = LoggerFactory.getLogger(Authenticator.class);

	public static String authenticate(String token){
		try {
			String urlString = AgentService.get().getSsoAuthUrl()
				+ "?" + Globals.TOKEN_PARAM + "=" + token;

			URL url = new URL(urlString);
			InputStream in = url.openStream();

			XPath xpath = XPathFactory.newInstance().newXPath();
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document document = builder.parse(in);
			String result = (String)xpath.evaluate("/" + Globals.AUTH_USERNAME_TAG, document, XPathConstants.STRING);
			in.close();

			return result;

		} catch (Exception e) {
			log.error("while submitting token param to sso server!", e);
		}
		return null;
	}
}
